package dbu.dbase.version3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import dbu.dbase.DBaseStructure;
import dbu.dbase.DataTypes;


/**
 * Field Descriptor. (One for each field in the table)
 * @author otomov
 */
public class FieldDescriptor extends DBaseStructure {

	/** Field Descriptor terminator 0x0D. */
	public static byte TERMINATER = 0x0D;

	/**
	 * Field name in ASCII (zero-filled).
	 */
	private String fieldName;

	/**
	 * Field type in ASCII (C, D, L, M or N).
	 */
	private DataTypes fieldType;

	/**
	 * Field length in binary.
	 */
	private byte fieldLength;

	/**
	 * Field decimal count in binary.
	 */
	private byte fieldDecimalCount;

	/**
	 * Work area ID.
	 */
	private byte workAreaID;

	/**
	 * SET FIELDS flag.
	 */
	private byte setFieldsFlag;

	/**
	 * Read  
	 * @param stream
	 * @throws IOException
	 */
	@Override
	public int read(InputStream stream) throws IOException {
		/** 1 byte 	0x0D stored as the Field Descriptor terminator. */
		int check = stream.read();
		if (check == TERMINATER) {
			return 1;
		}
		/** 11 bytes */
		fieldName = (char)check + readString(stream, 10);
		/** 1 byte */
		fieldType = DataTypes.getBySymbol((char) stream.read());
		/** 4 bytes 	Field data address (address is set in memory; not useful on disk). */
		readBuff(stream, 4);
		/** 1 byte */
		fieldLength = readByte(stream);
		/** 1 byte */
		fieldDecimalCount = readByte(stream);
		/** 2 bytes 	Reserved for dBASE III PLUS on a LAN. */
		readBuff(stream, 2);
		/** 1 byte */
		workAreaID = readByte(stream);
		/** 2 bytes 	Reserved for dBASE III PLUS on a LAN. */
		readBuff(stream, 2);
		/** 1 byte */
		setFieldsFlag = readByte(stream);
		/** 8 bytes 	Reserved. */
		readBuff(stream, 8);
		return 32;
	}

	/**
	 * Write 
	 * @param stream
	 * @throws IOException
	 */
	public void write(OutputStream stream) throws IOException {
		/** 11 bytes */
		writeString(stream, fieldName, 11);
		/** 1 byte */
		stream.write(fieldType.getSymbol());
		/** 4 bytes 	Field data address (address is set in memory; not useful on disk). */
		stream.write(new byte[] {0, 0, 0, 0});
		/** 1 byte */
		stream.write(fieldLength);
		/** 1 byte */
		stream.write(fieldDecimalCount);
		/** 2 bytes 	Reserved for dBASE III PLUS on a LAN. */
		stream.write(new byte[] {0, 0});
		/** 1 byte */
		stream.write(workAreaID);
		/** 2 bytes 	Reserved for dBASE III PLUS on a LAN. */
		stream.write(new byte[] {0, 0});
		/** 1 byte */
		stream.write(setFieldsFlag);
		/** 8 bytes 	Reserved. */
		stream.write(new byte[] {0, 0, 0, 0, 0, 0, 0, 0});
	}

	public String getFieldName() {
		return fieldName;
	}

	public DataTypes getFieldType() {
		return fieldType;
	}

	public byte getFieldLength() {
		return fieldLength;
	}

	public byte getFieldDecimalCount() {
		return fieldDecimalCount;
	}
}
